package cn.ex.de001.project.controller;

import cn.ex.de001.common.utils.Result;
import cn.ex.de001.common.utils.tokenUtils.Token;
import cn.ex.de001.exception.BaseException;
import cn.ex.de001.project.service.UserServiceImpl;
import cn.ex.de001.project.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class LogController {
    @Autowired
    private UserServiceImpl userServiceImpl;

    @GetMapping("/login")//用户登入
    public Result<String> login(@Param("account") String account, @Param("password") String password){
        User user = userServiceImpl.login(account);
        if (user==null){
            throw new BaseException("账号不存在");
        } else if(user.getPassword().equals(password)){//密码正确
            Token.map.remove(account);//移除之前的token
            String token = Token.sign(account);//签发新的token
            assert token != null;
            Token.map.put(account,token);//将新的token移入有效token
            return Result.success(token);
        } else {
            throw new BaseException("账号/密码错误");
        }
    }

    @GetMapping("/exit") //用户退出
    public Result<String> exit(@Param("account") String account){
        try {
            Token.map.remove(account);//移除之前的token
            return Result.success();
        }catch (Exception e){
            throw new BaseException("退出登录失败,请重试");
        }
    }

}
